package com.gulimall.auth.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.common.utils.R;
import com.gulimall.auth.feign.MemberFeignService;
import com.gulimall.auth.utils.HttpUtils;
import com.common.vo.MemberResponseVO;
import com.gulimall.auth.vo.SocialUser;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

import static com.common.constant.AuthServerConstant.LOGIN_USER;

/**
 * @author mayifan
 * @version 1.0
 * @date 2025-01-06 17:11
 */
@Controller
public class OAuth2Controller {

    @Autowired
    MemberFeignService memberFeignService;

    @GetMapping("/oauth2.0/gitee/success")
    public String gitee(@RequestParam("code") String code, HttpSession session, RedirectAttributes attributes) throws Exception {

        //根据自己的信息设置value
        Map<String, String> map = new HashMap<>();
        map.put("grant_type","authorization_code");
        map.put("code",code);
        map.put("client_id","4b5fe5d6bc372f1340d53c7d5dc53f9a14fb643e16429299d2aae6f55237da74");
        map.put("redirect_uri","http://auth.gulimall.com/oauth2.0/gitee/success");
        map.put("client_secret","0216a5de603f2050ace4bc220b91dc5d0279b330e5a197b0b18c57b6ae7abf89");
        HttpResponse response = HttpUtils.doPost("https://gitee.com", "/oauth/token", "post", new HashMap<>(), map,new HashMap<>());
//        获取访问令牌

        Map<String, String> errors = new HashMap<>();
        if(response.getStatusLine().getStatusCode()==200){

            String s = EntityUtils.toString(response.getEntity());
            SocialUser socialUser = JSON.parseObject(s,SocialUser.class);
            R r = memberFeignService.oauth2Login(socialUser);
            if(r.getCode()==0){
//                登录成功
                String jsonString = JSON.toJSONString(r.get("data"));
                MemberResponseVO memberResponseVo = JSON.parseObject(jsonString, new TypeReference<MemberResponseVO>() {
                });
                session.setAttribute(LOGIN_USER,memberResponseVo);
                return "redirect:http://gulimall.com";
            }else{
                // 2.2 否则返回登录页
                errors.put("msg", "登录失败，请重试");
                attributes.addFlashAttribute("errors", errors);
                return "redirect:http://auth.gulimall.com/login.html";
            }
        }else {
            errors.put("msg", "获得第三方授权失败，请重试");
            attributes.addFlashAttribute("errors", errors);
            return "redirect:http://auth.gulimall.com/login.html";
        }
    }
}
